package com.ray.woodencreate.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author bo shen
 * @Description: 短信验证码工具
 * @Class: MessageCodeUtil
 * @Package com.toptoday.woodencreate.util
 * @date 2018/11/5 11:27
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
public class MessageCodeUtil {
    /**
     *
     * 短信头
     */
   private static final String MSG_TOPIC = "TODAYTOP:MSGCODE:";

    /**
     * 创建验证码
     * @param phone 手机号
     * @return
     */
    public static String createCode(String phone){
        return null;
    }

    /**
     * 插入redis 默认5分钟
     * @param phone 手机号码
     * @param code 验证码
     */
    public static void instertRedis(String phone,String code) {
        //放入redis
        StringRedisTemplate stringRedisTemplate = SpringApplicationUtil.getBean(StringRedisTemplate.class);
        if(!ObjectUtils.isEmpty(stringRedisTemplate)){
            stringRedisTemplate.opsForValue().set(MSG_TOPIC + phone, code,5*60, TimeUnit.SECONDS);
        }
    }

    /**
     * 创建验证码
     * @param phone 手机号
     * @param code 验证码
     * @return
     */
    public static Boolean existCode(String phone,String code){
        //redisquchu
        StringRedisTemplate stringRedisTemplate = SpringApplicationUtil.getBean(StringRedisTemplate.class);
        if(!ObjectUtils.isEmpty(stringRedisTemplate)){
           String redisCode =  stringRedisTemplate.opsForValue().get(MSG_TOPIC + phone);
           Boolean result = org.apache.commons.lang.StringUtils.equals(redisCode,code);
           //校验成功删除key
           if(result){
               stringRedisTemplate.delete(MSG_TOPIC + phone);
           }
           return  result;
        }
        return false;
    }

}
